using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using System.Collections.Generic;

namespace EntityKit.Runtime
{
    public static partial class AudioKit
    {
        private static readonly Dictionary<GameObject, AudioSource> worldSources = new Dictionary<GameObject, AudioSource>();
        private static float worldVolumeDefault = 1f;
        private static float worldVolume;
        private static bool isWorldSoundMute;
        /// <summary>
        /// 世界音效音量
        /// </summary>
        public static float WorldVolume
        {
            get => worldVolume;
            set
            {
                worldVolume = Mathf.Clamp01(value);
                foreach (var source in worldSources.Values)
                {
                    if (source != null) 
                        source.volume = worldVolume;
                }
            }
        }
        
        /// <summary>
        /// 世界音效静音设置
        /// </summary>
        public static bool WorldMute
        {
            get => isWorldSoundMute;
            set
            {
                isWorldSoundMute = value;
                foreach (var source in worldSources.Values)
                {
                    if (source != null) 
                        source.mute = isWorldSoundMute;
                }
            }
        }
        
        /// <summary>
        /// 播放世界音效
        /// </summary>
        /// <param name="target">目标游戏对象</param>
        /// <param name="clip">音频剪辑</param>
        /// <param name="isLoop">是否循环</param>
        /// <param name="speed">播放速度</param>
        public static void PlayWorldSound(GameObject target, AudioClip clip, bool isLoop = false, float speed = 1)
        {
            if (!isInitialized || !ValidateTarget(target) || !ValidateClip(clip)) 
                return;
            
            // 获取或创建音频源
            if (!worldSources.TryGetValue(target, out AudioSource source))
            {
                source = AttachAudioSource(target, worldVolume, isWorldSoundMute);
                if (source == null) 
                    return;
                worldSources[target] = source;
            }
            
            // 配置音频源
            ConfigureAudioSource(source, clip, isLoop, speed);
            source.volume = worldVolume;
            source.mute = isWorldSoundMute;
            source.Play();
        }
        
        /// <summary>
        /// 停止目标对象的世界音效
        /// </summary>
        /// <param name="target">目标游戏对象</param>
        public static void StopWorldSound(GameObject target)
        {
            if (!isInitialized || !ValidateTarget(target)) 
                return;

            if (worldSources.TryGetValue(target, out AudioSource source) && source != null)
            {
                source.Stop();
            }
        }

        /// <summary>
        /// 暂停目标对象的世界音效
        /// </summary>
        /// <param name="target">目标游戏对象</param>
        public static void PauseWorldSound(GameObject target)
        {
            if (!isInitialized || !ValidateTarget(target)) 
                return;

            if (worldSources.TryGetValue(target, out AudioSource source) && source != null)
            {
                source.Pause();
            }
        }

        /// <summary>
        /// 恢复目标对象的世界音效
        /// </summary>
        /// <param name="target">目标游戏对象</param>
        public static void ResumeWorldSound(GameObject target)
        {
            if (!isInitialized || !ValidateTarget(target)) 
                return;

            if (worldSources.TryGetValue(target, out AudioSource source) && source != null)
            {
                source.UnPause();
            }
        }

        /// <summary>
        /// 停止所有世界音效
        /// </summary>
        public static void StopAllWorldSound()
        {
            if (!isInitialized) 
                return;

            foreach (var pair in worldSources)
            {
                if (pair.Value != null)
                {
                    pair.Value.Stop();
                }
            }
        }
        
        private static void WorldSoundInitialize()
        {
            WorldVolume = worldVolumeDefault;
        }
        
        private static void WorldSoundUpdate()
        {
            // 检查字典中的AudioSource，移除已销毁的对象和已播放完毕的非循环音效
            List<GameObject> toRemove = null;
            foreach (var pair in worldSources)
            {
                // 移除已销毁的对象
                if (pair.Key == null || pair.Value == null)
                {
                    toRemove ??= new List<GameObject>();
                    toRemove.Add(pair.Key);
                }
                // 移除已播放完毕的非循环音效（只移除AudioSource组件，不删除GameObject）
                else if (!pair.Value.isPlaying && !pair.Value.loop)
                {
                    toRemove ??= new List<GameObject>();
                    toRemove.Add(pair.Key);
                    
                    // 销毁AudioSource组件
                    Object.Destroy(pair.Value);
                }
            }

            if (toRemove != null)
            {
                foreach (var obj in toRemove)
                {
                    worldSources.Remove(obj);
                }
            }
        }
        
        private static void WorldSoundRelease()
        {
            foreach (var pair in worldSources)
            {
                if (pair.Value != null)
                {
                    Object.Destroy(pair.Value);
                }
            }
            
            worldSources.Clear();
        }
    }
}